<template>
  <div class="profile-container">
    <div class="profile-header">
      <h2>我的儿童</h2>
      <el-button type="primary" @click="showAddChildDialog">
        <el-icon><Plus /></el-icon>
        添加儿童
      </el-button>
    </div>

    <!-- 儿童列表 -->
    <div class="children-list">
      <el-empty
        v-if="!children.length"
        description="暂无绑定儿童"
      />
      <div v-else class="children-grid">
        <div v-for="child in children" :key="child.id" class="child-card">
          <div class="child-avatar">
            <el-avatar :size="60" :src="child.avatar || defaultAvatar">
              {{ child.name.substring(0, 1) }}
            </el-avatar>
            <div class="gender-icon" :class="child.gender === '男' ? 'boy' : 'girl'">
              <el-icon><Male v-if="child.gender === '男'" /><Female v-else /></el-icon>
            </div>
          </div>
          <div class="child-info">
            <h3>{{ child.name }}</h3>
            <p class="child-details">
              {{ calculateAge(child.birthday) }}岁 | {{ child.gender === '男' ? '小王子' : '小公主' }}
            </p>
            <p class="child-birth">生日：{{ formatDate(child.birthday) }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加儿童对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="添加儿童"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="childForm"
        :rules="rules"
        label-width="80px"
        class="child-form"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="childForm.name" placeholder="请输入儿童姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="childForm.gender">
            <el-radio label="男">男孩</el-radio>
            <el-radio label="女">女孩</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker
            v-model="childForm.birthday"
            type="date"
            placeholder="选择出生日期"
            :disabled-date="disabledDate"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAddChild" :loading="loading">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Plus, Male, Female } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { get, post } from '@/utils/request'

const defaultAvatar = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'

// 儿童列表数据
const children = ref([])
const loading = ref(false)

// 获取儿童列表
const fetchChildren = async () => {
  try {
    const data = await get('/user/child/list')
    children.value = data
  } catch (error) {
    console.error('获取儿童列表错误:', error)
  }
}

// 添加儿童表单
const dialogVisible = ref(false)
const formRef = ref(null)
const childForm = ref({
  name: '',
  gender: '男',
  birthday: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入儿童姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  birthday: [
    { required: true, message: '请选择出生日期', trigger: 'change' }
  ]
}

// 禁用未来日期
const disabledDate = (time) => {
  return time.getTime() > Date.now()
}

// 显示添加对话框
const showAddChildDialog = () => {
  dialogVisible.value = true
  childForm.value = {
    name: '',
    gender: '男',
    birthday: ''
  }
}

// 添加儿童
const handleAddChild = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        await post('/user/child/add', childForm.value)
        ElMessage.success('添加成功')
        dialogVisible.value = false
        fetchChildren() // 重新获取列表
      } catch (error) {
        console.error('添加儿童错误:', error)
      } finally {
        loading.value = false
      }
    }
  })
}

// 计算年龄
const calculateAge = (birthday) => {
  if (!birthday) return '--'
  const birthDate = new Date(birthday)
  const today = new Date()
  let age = today.getFullYear() - birthDate.getFullYear()
  const monthDiff = today.getMonth() - birthDate.getMonth()
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
    age--
  }
  return age
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '--'
  const d = new Date(date)
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
}

// 页面加载时获取列表
onMounted(() => {
  fetchChildren()
})
</script>

<style scoped>
.profile-container {
  padding: 24px;
}

.profile-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.profile-header h2 {
  font-size: 24px;
  color: #333;
  margin: 0;
}

.children-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 24px;
  margin-top: 24px;
}

.child-card {
  background: white;
  border-radius: 16px;
  padding: 24px;
  display: flex;
  align-items: center;
  gap: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
}

.child-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
}

.child-avatar {
  position: relative;
}

.gender-icon {
  position: absolute;
  bottom: -4px;
  right: -4px;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
}

.gender-icon.boy {
  background: var(--el-color-primary);
  color: white;
}

.gender-icon.girl {
  background: #ff69b4;
  color: white;
}

.child-info {
  flex: 1;
}

.child-info h3 {
  margin: 0 0 8px;
  font-size: 18px;
  color: #333;
}

.child-details {
  color: #666;
  margin: 0 0 4px;
  font-size: 14px;
}

.child-birth {
  color: #999;
  margin: 0;
  font-size: 13px;
}

.child-form {
  padding: 20px 0;
}

:deep(.el-dialog__body) {
  padding-top: 10px;
}

:deep(.el-form-item:last-child) {
  margin-bottom: 0;
}
</style> 